package com.nsgf.library.ui.product;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import static com.nsgf.library.data.api.APIs.APP_GH_ID;

import android.app.VoiceInteractor;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.AddressBean;
import com.nsgf.library.data.bean.ConfirmOrderBean;
import com.nsgf.library.data.bean.LibraryInfo;
import com.nsgf.library.data.bean.Shop;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.event.EventMsg;
import com.nsgf.library.event.RxBus;
import com.nsgf.library.ui.adapter.ConfirmOrderAdapter;
import com.nsgf.library.ui.mine.AddressListActivity;
import com.nsgf.library.ui.page.BaseActivity;
import com.nsgf.library.ui.page.LoginActivity;
import com.nsgf.library.ui.page.StateHolder;
import com.nsgf.library.utils.StringUtil;
import com.nsgf.library.utils.ToastUtils;
import com.nsgf.library.widget.prckerview.OptionsPickerView;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhht.htzx.BR;
import com.zhht.htzx.R;
import com.zhht.htzx.databinding.ActivityConfirmOrderBinding;
import com.zhht.htzx.ui.OrderListActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;

public class ConfirmOrderActivity extends BaseActivity {

    private ConfirmOrderStates mStates;

    private ActivityConfirmOrderBinding mBinding;

    private AccountRequester mAccountRequester;

    private ConfirmOrderAdapter adapter;
    private ArrayList<Shop.ValidListBean> shops = new ArrayList<>();


    JsonObject params = new JsonObject();
    JsonArray jsonArray = new JsonArray();

    @Override
    protected void initViewModel() {
        mAccountRequester = new AccountRequester();
        mStates = getActivityScopeViewModel(ConfirmOrderStates.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_confirm_order, BR.vm, mStates)
                .addBindingParam(BR.click, new ClickProxy());
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getLifecycle().addObserver(mAccountRequester);

        if (StringUtil.isEmpty(UserInfo.getInstance().getTokenValue())) {
            startActivity(new Intent().setClass(this, LoginActivity.class));
            finish();
        }

        mBinding = (ActivityConfirmOrderBinding) getBinding();
        ArrayList<Shop.ValidListBean> originalShops = getIntent().getParcelableArrayListExtra("data");
        shops = new ArrayList<>();

        // 创建新的过滤集合，复制所有属性
        for (Shop.ValidListBean originalShop : originalShops) {
            Shop.ValidListBean filteredShop = new Shop.ValidListBean();
            // 复制所有基本属性
            filteredShop.setCartId(originalShop.getCartId());
            filteredShop.setSpecifications(originalShop.getSpecifications());
            filteredShop.setTenantName(originalShop.getTenantName());

            // 创建新的规格列表，只包含选中的规格
            ArrayList<Shop.ValidListBean.SpecificationsBean> filteredSpecs = new ArrayList<>();
            for (Shop.ValidListBean.SpecificationsBean spec : originalShop.getSpecifications()) {
                if (spec.isSelected()) {
                    // 创建新的规格对象并复制所有属性
                    Shop.ValidListBean.SpecificationsBean newSpec = new Shop.ValidListBean.SpecificationsBean();
                    newSpec.setId(spec.getId());
                    newSpec.setCount(spec.getCount());
                    newSpec.setPrice(spec.getPrice());
                    newSpec.setProperty(spec.getProperty());
                    newSpec.setSku(spec.getSku());
                    newSpec.setSpu(spec.getSpu());
                    newSpec.setSpuName(spec.getSpuName());
                    newSpec.setPicUrl(spec.getPicUrl());
                    newSpec.setSelected(spec.isSelected());
                    filteredSpecs.add(newSpec);
                }
            }
            filteredShop.setSpecifications(filteredSpecs);
            shops.add(filteredShop);
        }

        mStates.titleBar.set("确认订单");


        for (Shop.ValidListBean shop : shops) {

            for (Shop.ValidListBean.SpecificationsBean specificationsBean : shop.getSpecifications()) {

                JsonObject jsonObject = new JsonObject();
                if (StringUtil.isEmpty(specificationsBean.getId()))
                    jsonObject.addProperty("skuId", specificationsBean.getSku().getId());
                else
                    jsonObject.addProperty("cartId", specificationsBean.getId());
                jsonObject.addProperty("count", specificationsBean.getCount());
                jsonArray.add(jsonObject);

            }

        }

        getHttpParams();

        mAccountRequester.getLibraryInfo().observe(this, new Observer<ResponseStatus<LibraryInfo>>() {
            @Override
            public void onChanged(ResponseStatus<LibraryInfo> libraryInfoResponseStatus) {
                getController().dismissLoading();
                if (libraryInfoResponseStatus.getResponseCode() == 0) {

                    EventMsg eventMsg = new EventMsg();
                    eventMsg.setMsg("refresh");
                    EventBus.getDefault().post(eventMsg);
                    //支付成功改变订单状态

                    if (StringUtil.isEmpty(libraryInfoResponseStatus.getData().getPayOrderId())) {
                        mAccountRequester.setUpdatePayStatus(libraryInfoResponseStatus.getData().getId());
                    } else {
//                        ToastUtils.showShortToast("订单创建成功，支付功能待调试");
                        payOrderId = libraryInfoResponseStatus.getData().getPayOrderId();
                        adapayOrder();
//                        startActivity(new Intent().setClass(ConfirmOrderActivity.this, OrderListActivity.class));
//                        finish();
                    }
                }
            }
        });

        mAccountRequester.getSrcSuccess().observe(this, new Observer<ResponseStatus<String>>() {
            @Override
            public void onChanged(ResponseStatus<String> stringResponseStatus) {
                if (stringResponseStatus.getResponseCode() == 0) {
                    startActivity(new Intent().setClass(ConfirmOrderActivity.this, OrderListActivity.class));
                    finish();
                }
            }
        });

        mAccountRequester.getConformOrderResult().observe(this, new Observer<ResponseStatus<ConfirmOrderBean>>() {
            @Override
            public void onChanged(ResponseStatus<ConfirmOrderBean> confirmOrderBeanResponseStatus) {
                if (confirmOrderBeanResponseStatus.getResponseCode() == 0) {
                    mStates.confirmOrder.set(confirmOrderBeanResponseStatus.getData());
                    if (!mStates.confirmOrder.get().getCoupons().isEmpty()) {
                        mBinding.checkboxConfirmOrderCoupons.setVisibility(VISIBLE);
                        mBinding.tvConfirmOrderNotCoupons.setVisibility(GONE);
                        mBinding.checkboxConfirmOrderCoupons.setText(mStates.confirmOrder.get().getCoupons().get(0).getName());

                    } else {
                        mBinding.checkboxConfirmOrderCoupons.setVisibility(GONE);
                        mBinding.tvConfirmOrderNotCoupons.setVisibility(VISIBLE);
                    }

                    if (!mStates.confirmOrder.get().getPromotions().isEmpty()) {
                        mStates.description.set(mStates.confirmOrder.get().getPromotions().get(0).getDescription());
                    } else mStates.description.set("");
                }
            }
        });
        // 初始化视图
        initViews();
        // 初始化数据
        initData();
        // 设置监听器
        setupListeners();
    }

    private void initViews() {

        // 设置RecyclerView
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mBinding.checkbox.setChecked(false);
        mBinding.checkbox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            mStates.pointStatus.set(isChecked);
            getHttpParams();
        });
        mBinding.checkboxConfirmOrderCoupons.setChecked(false);
        mBinding.checkboxConfirmOrderCoupons.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if (isChecked) {
                    mStates.couponId.set(mStates.confirmOrder.get().getCoupons().get(0).getId());
                } else mStates.couponId.set(null);
                getHttpParams();

            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 处理intent数据
        Uri data = intent.getData();
        if (data != null) {
            String action = data.getQueryParameter("action"); // 获取参数
            // 执行相应操作
            ToastUtils.showShortToast(action);
        }
    }

    private void getHttpParams() {

        params.add("items", jsonArray);
        params.addProperty("deliveryType", "1");
        params.addProperty("pointStatus", mStates.pointStatus.get());
        params.addProperty("couponId", mStates.couponId.get());
        mAccountRequester.getSettlement(params);

    }

    private void initData() {

        // 模拟数据，实际应用中应该从数据库或网络获取
        adapter = new ConfirmOrderAdapter(this, shops);
        mBinding.recyclerView.setAdapter(adapter);

        mAccountRequester.getDefaultAddress();
        mAccountRequester.getAddressResult().observe(this, new Observer<ResponseStatus<AddressBean>>() {
            @Override
            public void onChanged(ResponseStatus<AddressBean> addressBeanResponseStatus) {
                if (addressBeanResponseStatus.getResponseCode() == 0) {

                    if (null == addressBeanResponseStatus.getData()) {
                        mBinding.tvConfirmOrderAddress.setVisibility(VISIBLE);
                        mBinding.llConfirmOrderAddress.setVisibility(GONE);
                        mStates.addressBeanState.set(new AddressBean());
                    } else {
                        mBinding.tvConfirmOrderAddress.setVisibility(GONE);
                        mBinding.llConfirmOrderAddress.setVisibility(VISIBLE);
                        mStates.addressBeanState.set(addressBeanResponseStatus.getData());
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mStates.addressBeanState.get().getId() != 0) {
            mAccountRequester.getAddress(String.valueOf(mStates.addressBeanState.get().getId()));
        }
    }

    private void setupListeners() {

        mBinding.btnCheckout.setOnClickListener(v -> {
            getController().displayLoading("正在创建订单...");
            // 处理结算逻辑
            JsonObject params = new JsonObject();
            JsonArray jsonArray = new JsonArray();
            // 遍历 items 并转换为 JsonObject 后添加到 JsonArray 中
            for (ConfirmOrderBean.ItemsBean item : mStates.confirmOrder.get().getItems()) {
                // 使用 Gson 将对象转换为 JsonObject
                JsonObject jsonObject = new Gson().toJsonTree(item).getAsJsonObject();
                jsonArray.add(jsonObject);
            }
            params.add("items", jsonArray);
            params.addProperty("couponId", mStates.couponId.get());
            params.addProperty("pointStatus", mStates.pointStatus.get());
            params.addProperty("deliveryType", mStates.deliveryType.get());
            params.addProperty("addressId", mStates.addressBeanState.get().getId());
            params.addProperty("receiverName", mStates.addressBeanState.get().getName());
            params.addProperty("receiverMobile", mStates.addressBeanState.get().getMobile());
            params.addProperty("remark", mStates.remark.get());
            mAccountRequester.createOrder(params);
        });

    }

    public static class ConfirmOrderStates extends StateHolder {

        public final State<ConfirmOrderBean> confirmOrder = new State<>(new ConfirmOrderBean());
        public final State<AddressBean> addressBeanState = new State<>(new AddressBean());

        public final State<Boolean> pointStatus = new State<>(false);
        public final State<Integer> couponId = new State<>(null);
        public final State<String> description = new State<>("");
        public final State<String> deliveryType = new State<>("2");
        public final State<String> deliveryTypeSrc = new State<>("用户自提");
        public final State<String> remark = new State<>("");


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1001) {
                mStates.addressBeanState.set(data.getParcelableExtra("data"));
                mBinding.tvConfirmOrderAddress.setVisibility(GONE);
                mBinding.llConfirmOrderAddress.setVisibility(VISIBLE);
            }
        }
    }

    public class ClickProxy {

        public void deliveryType() {

            OptionsPickerView<ConfirmOrderBean.DeliveryTypeListBean> mOptionsPickerView = new OptionsPickerView.Builder(ConfirmOrderActivity.this
                    , new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {

                    mStates.deliveryTypeSrc.set(mBinding.getVm().confirmOrder.get().getDeliveryTypeList().get(options1).getPickerViewText());
                    mStates.deliveryType.set(String.valueOf(mBinding.getVm().confirmOrder.get().getDeliveryTypeList().get(options1).getCode()));
                }
            }).build();
            mOptionsPickerView.setPicker(mBinding.getVm().confirmOrder.get().getDeliveryTypeList());
            mOptionsPickerView.show();
        }

        public void openAddressList() {
            startActivityForResult(new Intent()
                    .putExtra("data", mStates.addressBeanState.get())
                    .setClass(ConfirmOrderActivity.this,
                            AddressListActivity.class), 1001);

        }


    }

    String payType = "2";
    private String payOrderId = "";

    private void adapayOrder() {

        if ("1".equals(payType)) {
//            HttpModel.orderPay(this, orderId, payType, new HttpOnNextListener<SecondhandPayBean>() {
//                @Override
//                public void onSuccess(SecondhandPayBean baseResponse) {
//
//                    if ("1".equals(payType)) {
//                        // 固定前缀
//                        String topic = "alipays://platformapi/startapp?saId=10000007&qrcode=";
//                        // 从汇付正扫接口获取的参数（以下值仅为示例）
//                        String qrcodeUrl = baseResponse.getExpend().getQrcode_url();
//                        // 字符串拼接
//                        String jumpUrl = topic + qrcodeUrl;
//                        // 按以上示例拼接得出结果
//                        // jumpUrl 为 alipays://platformapi/startapp?saId=10000007&qrcode=https://qr.alipay.com/bax02911brluc2xieoph6001
//
//                        Intent intent = new Intent();
//                        intent.setAction("android.intent.action.VIEW");
//                        // jumpUrl 为先前示例中拼装的 url
//                        Uri contentUrl = Uri.parse(jumpUrl);
//                        intent.setData(contentUrl);
//                        startActivity(intent);
//                    }
//                }
//
//                @Override
//                public void onFail(String e) {
//
//                }
//            });
        } else if ("2".equals(payType)) {

            IWXAPI api = WXAPIFactory.createWXAPI(this, APIs.APP_ID);

            WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
            req.userName = APP_GH_ID; // 填小程序原始id
            req.path = "Client_Lite/cashier/cashier?price=" + mStates.confirmOrder.get().getPrice().getPayPriceSrc() + "&payOrderId=" + payOrderId;
//            req.path = "subPack_one/address_add/address_add?params=" + mStates.confirmOrder.get().getPrice().getPayPrice() + "&token=" + UserInfo.getInstance().getTokenValue() + "&orderType=1&orderId=" + orderId;
            req.miniprogramType = APIs.MINIPROGRAM_TYPE_PREVIEW;// 可选打开 开发版，体验版和正式版
            api.sendReq(req);
            // 延迟2秒后跳转到订单列表页面
            mBinding.getRoot().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent().setClass(ConfirmOrderActivity.this, OrderListActivity.class));
                    finish();
                }
            }, 4000);

        } else {


//            HttpModel.balanceRecycleFish(orderId, new HttpOnNextListener<BaseResponse>() {
//                @Override
//                public void onSuccess(BaseResponse baseResponse) {
//                    showToast(baseResponse.getMsg());
//                    finish();
//
//                }
//
//                @Override
//                public void onFail(String e) {
//                    getController().dismissLoading();
//
//                }
//            });
        }
    }
}
